﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RoverStudio.Common.Controller;
using System.IO.Ports;

namespace TICC2480MTClient
{
    public class TIRoverController : ITankController
    {
        MTSerialClient serialClient;
        SerialPort sp = new SerialPort();
        public event EventHandler<PacketEventArgs> CommandReceived;

        public TIRoverController()
        {
        }

        public string SelectedPort
        {
            get;
            set;
        }

        public void Start()
        {
            if (sp.IsOpen)
                sp.Close();
            sp.PortName = SelectedPort;
            sp.BaudRate = 9600;
            
            sp.Open();

            serialClient = new MTSerialClient(sp.BaseStream);
            serialClient.CommandReceived += new EventHandler<PacketEventArgs>(serialClient_CommandReceived);

        }

        public void Bind()
        {
            var p = SerialPacket.CreateBindDeviceCommand(true, 2, null);
            serialClient.SendCommand(p);
        }

        void serialClient_CommandReceived(object sender, PacketEventArgs e)
        {
            if (CommandReceived != null)
                CommandReceived(sender, e);
            //throw new NotImplementedException();
        }

        #region ITankController Members

        public void MoveTank(double left, double right, double time)
        {
            int ileft = (int)(left*20000);
            int iright = (int)(right*20000);

            var data = new byte[]{
                (byte)(ileft & 0xFF),
                (byte)((ileft>>8) & 0xFF),
                (byte)(iright&0xFF),
                (byte)((iright>>8) & 0xFF),
            };

            // dest:
            // FFFC: routers and coordinator
            // FFFD: all devices turned on
            // FFFE: binding
            // FFFF: all devices in network


            // binding, command=2
            var p = SerialPacket.CreateSendDataRequestCommand(0xFFFE, 2, true, 2, data);
            try
            {
                serialClient.SendCommand(p);
            }
            catch
            {
            }
        }

        #endregion
    }
}
